let express = require('express')
let router = express.Router()
let timeStamp = require("time-stamp")
let Query = require("../tools/db")
let { getToken, verifyToken, api_url, suo } = require("../config/index")
let formidable = require("formidable")
let path = require("path")
let fs = require("fs")
const md5 = require('md5')

// 这个页面中的接口都需要有权限
// 获取视频资源
router.get("/videoplay", async (req, res, next) => {
    let { id } = req.query
    let mid = "e9b9972f-387c-40ec-87dc-3a0881627784"
    if (!id) {
        next("请传递视频的id")
        return
    }
    if (!mid) {
        next("请登录")
        return
    }
    let sql = `SELECT id,CONCAT("${api_url}","uploads/video/",video_src) AS video_src FROM e_video WHERE id='${id}' `
    let [, result] = await Query(sql)
    res.send({
        status: 200,
        msg: "ok",
        result: result[0].video_src
    })

})

// 报名课程  生成订单
router.post("/study", async (req, res, next) => {
    let { id } = req.body
    let mid = "e9b9972f-387c-40ec-87dc-3a0881627784"
    if (!mid) {
        next("请登录")
    }
    // 1.查询当前用户是否报过该课程
    let sql1 = `SELECT * FROM e_order WHERE mid='${mid}' AND cid='${id}'`
    let [, result1] = await Query(sql1)
    if (result1.length > 0) {
        next("已报名该课程 去学习")
        return
    } else {
        // 2.创建订单信息  
        let oid = timeStamp("YYYYMMDDHHmmss") + (Math.random() + "").substring(2, 8)
        let createdate = Date.now()
        let sql2 = `INSERT INTO e_order (oid,cid,mid,createdate) VALUES ('${oid}','${id}','${mid}','${createdate}')`
        let [, result2] = await Query(sql2)
        if (result2.affectedRows > 0) {
            res.send({
                status: 200,
                msg: "报名成功"
            })
        } else {
            next("请稍后再试")
            return
        }
    }

})

// 获取用户信息
router.get("/user", async (req, res, next) => {
    let { mid = "" } = req.query
    if (!mid) {
        next("请登录")
        return
    }
    let sql = `SELECT id,mid,username,password,realname,sex,birthdate,head_photo_url FROM e_member WHERE mid='${mid}'`
    let [, result] = await Query(sql)
    result[0].head_photo_url = api_url + "uploads/avatar/" + result[0].head_photo_url
    res.send({
        status: 200,
        msg: "ok",
        result: result[0]
    })
})

// 更新用户头像
router.post("/uploadFile", (req, res, next) => {
    // let {mid=""}=req.body
    let mid = "e9b9972f-387c-40ec-87dc-3a0881627784"
    if (!mid) {
        next("请登录")
        return
    }
    let form = formidable({
        uploadDir: "temdir"
    })
    form.parse(req, async (err, fields, files) => {
        if (files.f.size == 0) {
            next("请传递一个文件")
            return
        }
        // 1.把临时存放的文件 放到uploads/avatar
        let sourcePath = files.f.filepath
        // 存放使用年月日时分秒+6位随机数
        let filename = timeStamp("YYYYMMDDHHmmss") + (Math.random() + "").substring(2, 8)
        let ext = path.extname(files.f.originalFilename)
        let newPath = path.join(__dirname, "../uploads/avatar", filename + ext)
        fs.renameSync(sourcePath, newPath)
        // 2.修改数据库中 头像地址
        let sql1 = `UPDATE e_member SET head_photo_url='${filename}${ext}' WHERE mid='${mid}'`
        let [, result1] = await Query(sql1)
        if (result1.affectedRows > 0) {
            res.send({
                status: 200,
                msg: "ok",
                result: `${api_url}uploads/avatar/${filename}${ext}`
            })
        } else {
            next("请重试")
            return
        }
    })

})

// 更新用户信息  不更改用户名
router.post("/user", async (req, res, next) => {
    let { realname, sex, birthdate, city } = req.body
    let mid = "4f95ae54-89a7-45d0-bc48-657a6dbf95d1"
    if (!mid) {
        next("请登录")
        return
    }
    let sql1 = `UPDATE e_member SET realname,sex,birthdate,city WHERE mid='${mid}'`
    let [, result1] = await Query(sql1)
    if (result1.affectedRows > 0) {
        res.send({
            status: 200,
            msg: "ok"
        })
    } else {
        next("请重试")
        return
    }

})

// 查看订单
router.get("/orders", async (req, res, next) => {
    // let { mid = "" } = req.query
    let mid = "92f9793a-7c42-45c3-895b-4f6f1845def4"
    if (!mid) {
        next("请登录")
        return
    }
    let sql = `SELECT title,mid,subject_name,CONCAT("${api_url}","uploads/course/",image_src) AS image_src,area_name FROM e_course AS c JOIN e_order AS o ON c.cid=o.cid WHERE o.mid='${mid}' `
    let [, result] = await Query(sql)
    res.send({
        status: 200,
        msg: "ok",
        result
    })
})


module.exports = router